package sample.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import sample.model.Address;

import java.io.*;
import java.util.List;

public class AddressUtils extends LogUtils{

    public static JSONObject address = null;

    static {

        /**File file = new File(System.getProperty("user.dir")+"/address.json");
        String jsonstr = null;
        try {
            jsonstr = FileUtils.readFileToString(file);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("read address.json cause exception:{}", e);
        }**/

        InputStream is = AddressUtils.class.getClassLoader().getResourceAsStream("address.json");
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        StringBuffer buffer = new StringBuffer();
        String line = null;
        try {
            while ((line = in.readLine()) != null) {
                buffer.append(line);            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("read address.json cause exception:{}", e);
        }

        address = JSONObject.parseObject(buffer.toString());
    }

    public static List<Address> getAddress(String code){
        JSONArray parr = address.getJSONArray(code == null ? "province" : code);
        //System.out.println(parr);
        return JSONObject.parseArray(parr.toJSONString(), Address.class);
    }

    public static void main(String[] args) {
        System.out.println(getAddress(null));
    }
}
